package android.fwirk;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;

import android.fwirk.facebook.FacebookStatus;
import android.fwirk.facebook.FacebookUser;
import android.fwirk.obj.CustomProgressDialog;
import android.fwirk.obj.StatusMessage;
import android.fwirk.obj.StatusMessageAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class FacebookActivity extends Activity implements OnItemLongClickListener {
	
	ListView timeLine;
	StatusMessage empty;
	StatusMessage more;
	StatusMessageAdapter smAdapter;
	CustomProgressDialog progress;
	LinearLayout moreProgress;
	Intent intent;
	boolean gotFacebookStatus;
	boolean hasFacebookStatusNext;
	int tID=0;
	private int DIALOG_PROGRESS=0;
	private int DIALOG_SIGNOUT=1;
	private AlertDialog signoutDialog;
	final static int MENU_RELOAD=0;
	final static int MENU_SIGNOUT=1;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.facebook);
    	timeLine=(ListView)findViewById(R.id.facebookTimeline);
    	empty=new StatusMessage();
        empty.setDrawID(R.drawable.alert);
        empty.setStatus("No recent news feed yet.");
        more=new StatusMessage();
        more.setDrawID(R.drawable.alert);
        more.setStatus("More");
        more.setMisc("Touch and hold to expand");
        smAdapter=new StatusMessageAdapter(this, R.layout.row);
        timeLine.setAdapter(smAdapter);
        timeLine.setOnItemLongClickListener(this);
        progress = new CustomProgressDialog(this);
        progress.setText("Retrieving news feed...");
		progress.setImage1(R.drawable.facebookd);
		progress.setImage1Visibility(View.VISIBLE);
		progress.setImage2Visibility(View.GONE);
		progress.setImage3Visibility(View.GONE);
		moreProgress=(LinearLayout) findViewById(R.id.moreBar);
		moreProgress.setVisibility(View.GONE);
		Builder bd=new Builder(this);
		signoutDialog = bd.setMessage("Sign out?").setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (which == DialogInterface.BUTTON_POSITIVE) {
							showDialog(DIALOG_PROGRESS);
							new LogoutThread(logoutH, tID).start();
						}

					}
				}).setNegativeButton("No",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (which == DialogInterface.BUTTON_NEGATIVE) {
							dialog.dismiss();
						}

					}
				}).create();
		
		intent=new Intent(this,CustomDialogActivity.class);
		smAdapter.clear();
        smAdapter.add(empty);
    	gotFacebookStatus=false;
    	hasFacebookStatusNext=false;
    	tID++;
    	showDialog(DIALOG_PROGRESS);
        GetStatusThread pt=new GetStatusThread(getApplicationContext(),recentH,1,31,null,Const.TYPE_FACEBOOK,true,false,tID%Integer.MAX_VALUE);
        pt.start();
        WaitThread wt=new WaitThread(waitRecentH, null, null, pt, tID);
        wt.start();
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(requestCode==Const.ACTIVITY_VIEW) {
    		if(resultCode==RESULT_OK) {
    			hasFacebookStatusNext=false;
    			gotFacebookStatus=false;
        		tID++;
        		progress.setText("Retrieving news feed..."); 
        		progress.setImage1(R.drawable.facebookd);
        		showDialog(DIALOG_PROGRESS);
        		GetStatusThread pt=new GetStatusThread(getApplicationContext(),recentH,1,31,null,Const.TYPE_FACEBOOK,true,false,tID%Integer.MAX_VALUE);
                pt.start();
        		WaitThread wt=new WaitThread(waitRecentH, null, null, pt, tID%Integer.MAX_VALUE);
        		wt.start();
    		}
    	}
    }
	
	@Override
    protected Dialog onCreateDialog(int id) {
    	if(id==DIALOG_PROGRESS) {
    		return progress.getDialog();
    	}
    	else if(id==DIALOG_SIGNOUT) {
    		return signoutDialog;
    	}
    	return super.onCreateDialog(id);
    }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_BACK) {
			if(progress.isShowing()) {
				progress.hide();
			}
			else {
				showDialog(DIALOG_SIGNOUT);
			}
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			menu.add(0,MENU_RELOAD,0,"Reload News Feed")
				.setIcon(R.drawable.facebooke);
			menu.add(0,MENU_SIGNOUT,0,"Sign out")
			.setIcon(R.drawable.fwirk);
			return true;
		}
		
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			switch(item.getItemId()) {
				case MENU_RELOAD:
					hasFacebookStatusNext=false;
					gotFacebookStatus=false;
	        		tID++;
	        		progress.setText("Retrieving news feed..."); 
	        		progress.setImage1(R.drawable.facebookd);
	        		showDialog(DIALOG_PROGRESS);
	        		GetStatusThread pt=new GetStatusThread(getApplicationContext(),recentH,1,31,null,Const.TYPE_FACEBOOK,true,false,tID%Integer.MAX_VALUE);
	                pt.start();
	        		WaitThread wt=new WaitThread(waitRecentH, null, null, pt, tID%Integer.MAX_VALUE);
	        		wt.start();
					break;
				case MENU_SIGNOUT:
					showDialog(DIALOG_SIGNOUT);
					break;
			}
			return true;
		}

	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		if(arg0==timeLine) {
			StatusMessage sm=((StatusMessage)(timeLine.getItemAtPosition(arg2)));
			if(!(sm.getDrawID()==R.drawable.alert)) {
				Const.curStatusMessage=sm;
				startActivityForResult(intent, Const.ACTIVITY_VIEW);
			}
			else {
				if(sm.getStatus().equals("More")) {
					moreProgress.setVisibility(View.VISIBLE);
					hasFacebookStatusNext=false;
					gotFacebookStatus=false;
	        		tID++;
	        		smAdapter.remove(sm);
	        		StatusMessage m=smAdapter.getItem(smAdapter.getCount()-1);
	        		FacebookStatus fs=(FacebookStatus)m.getMsg();
	        		GetStatusThread pt=new GetStatusThread(getApplicationContext(),recentH,1,31,fs.getUpdatedTime(),Const.TYPE_FACEBOOK,true,true,tID%Integer.MAX_VALUE);
	                pt.start();
	        		WaitThread wt=new WaitThread(waitRecentH, null, null, pt, tID%Integer.MAX_VALUE);
	        		wt.start();
				}
			}
		}
		return false;
	}
	
	final Handler recentH = new Handler() {
        @Override
		public void handleMessage(Message msg) {
        	if(msg.getData().getInt("tID")==tID%Integer.MAX_VALUE) {	        	
	        	if(msg.getData().getBoolean("status") && msg.getData().getInt("type")==Const.TYPE_FACEBOOK) {
	        		gotFacebookStatus=true;
	        		progress.setImage1(R.drawable.facebooke);
	        		if(msg.getData().getBoolean("hasNext")) {
	        			hasFacebookStatusNext=true;
	        		}
	        	}
        	}
        }
    };
    
    final Handler waitRecentH = new Handler() {
        @Override
		public void handleMessage(Message msg) {
        	StatusMessage sm;
        	if(msg.getData().getInt("tID")==tID%Integer.MAX_VALUE) {
        		progress.hide();
	        	if(!gotFacebookStatus) {
	        		Toast.makeText(getApplicationContext(), "Could not retrieve Facebook timeline", Toast.LENGTH_SHORT).show();
	        	}
	        	else {
	        		smAdapter.clear();
	        		if(gotFacebookStatus) {
	        			Log.d("Test","recent facebook status");
	        			for(FacebookStatus s:Const.myFacebookStatus) {
	        				FacebookUser user=s.getOwner();
	        				sm=new StatusMessage();
	        				sm.setMsg(s);
	        				sm.setDrawID(R.drawable.defaultfacebookpic);
	        				String note="Anon: ";
	        				if(user!=null) {
								sm.setBitmap(user.getPic());	
								if(user.getName().length()>0) {
			        				note=user.getName()+": ";
			        			}
	        				}
	        				note=note+s.getMessage()+" "+s.getAttachDesc();
							sm.setStatus(note.replace("<br/>", ""));
		        			sm.setMisc(DateFormat.format("hh:mm:ss aa - MMM dd, yyyy", s.getUpdatedTime())+"");
		        			smAdapter.add(sm);
	        			}
	        		}
	        		if(smAdapter.isEmpty()) {
	        			smAdapter.add(empty);
	        		}
	        		else if(hasFacebookStatusNext) {
	        			smAdapter.add(more);
	        		}
	        		moreProgress.setVisibility(View.GONE);
	        		Toast.makeText(getApplicationContext(), "Retrieved news feed", Toast.LENGTH_SHORT).show();
	        	}
        	}
        }
    };
    
    final Handler logoutH = new Handler() {
        @Override
		public void handleMessage(Message msg) {
        	if(msg.getData().getInt("tID")==tID%Integer.MAX_VALUE) {	        	
	        	progress.hide();
        		finish();
        	}
        }
    };
}
